package lzh.com.customeroilactivity.activity;

import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v7.app.AlertDialog;
import android.view.Display;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.view.inputmethod.InputMethodManager;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import java.util.List;

import cn.bmob.v3.BmobQuery;
import cn.bmob.v3.exception.BmobException;
import cn.bmob.v3.listener.FindListener;
import cn.bmob.v3.listener.SaveListener;
import lzh.com.customeroilactivity.Bean.Company;
import lzh.com.customeroilactivity.NewBaseActivity;
import lzh.com.customeroilactivity.R;
import lzh.com.customeroilactivity.widget.OnWheelChangedListener;
import lzh.com.customeroilactivity.widget.WheelView;
import lzh.com.customeroilactivity.widget.adapters.ArrayWheelAdapter;

public class AddCompanyActivity extends NewBaseActivity implements View.OnClickListener, OnWheelChangedListener {

    private ImageButton back;
    private TextView title;
    private EditText detailName;
    private EditText name;
    private TextView person;
    private TextView industry;
    private TextView money;
    private TextView address;
    private EditText detailAddress;
    private TextView remarks;
    private RelativeLayout layout;
    private Button go;
    private TextView state;

    private WheelView mViewProvince;
    private WheelView mViewCity;
    private WheelView mViewDistrict;
    private TextView no;
    private TextView yes;

    private String companyName;
    private String ticketNumber;
    private String companyAddress;
    private String companyIphone;
    private String bankName;
    private String bankNumber;

    private SharedPreferences sharedPreferences;
    private int dataNumber = 0;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_add_company);
        sharedPreferences = this.getSharedPreferences("userData",MODE_PRIVATE);
        init();
    }

    private void init(){
        back = (ImageButton)findViewById(R.id.top_left_btn);
        title = (TextView)findViewById(R.id.title_bar);
        detailName = (EditText)findViewById(R.id.detail_name);
        name = (EditText)findViewById(R.id.name);
        person = (TextView)findViewById(R.id.person);
        industry = (TextView)findViewById(R.id.industry);
        money = (TextView)findViewById(R.id.money);
        address = (TextView)findViewById(R.id.address);
        detailAddress =(EditText) findViewById(R.id.detail_address);
        remarks = (TextView)findViewById(R.id.remarks);
        layout = (RelativeLayout)findViewById(R.id.layout);
        go = (Button) findViewById(R.id.go);
        state = (TextView)findViewById(R.id.state);

        title.setText("添加公司");
        back.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                finish();
            }
        });

        person.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                InputMethodManager imm = (InputMethodManager) getSystemService(INPUT_METHOD_SERVICE);
                if(imm != null){
                    imm.hideSoftInputFromWindow(getWindow().getDecorView().getWindowToken(), 0);
                }
                personClick();
            }
        });

        industry.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                InputMethodManager imm = (InputMethodManager) getSystemService(INPUT_METHOD_SERVICE);
                if(imm != null){
                    imm.hideSoftInputFromWindow(getWindow().getDecorView().getWindowToken(), 0);
                }
                industryClick();
            }
        });

        money.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                InputMethodManager imm = (InputMethodManager) getSystemService(INPUT_METHOD_SERVICE);
                if(imm != null){
                    imm.hideSoftInputFromWindow(getWindow().getDecorView().getWindowToken(), 0);
                }
                moneyClick();
            }
        });

        address.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                View view1 = LayoutInflater.from(AddCompanyActivity.this).inflate(R.layout.show_address,null);
                mViewProvince = (WheelView) view1.findViewById(R.id.id_province);
                mViewCity = (WheelView) view1.findViewById(R.id.id_city);
                mViewDistrict = (WheelView) view1.findViewById(R.id.id_district);
                no = (TextView)view1.findViewById(R.id.no);
                yes = (TextView)view1.findViewById(R.id.yes);

                final AlertDialog dialog = new AlertDialog.Builder(AddCompanyActivity.this,R.style.DialogStyle)
                        .setView(view1)
                        .create();
                dialog.show();
                setUpListener();
                setUpData();

                Window window = dialog.getWindow();
                window.setGravity(Gravity.BOTTOM);
                window.setWindowAnimations(R.style.popupAnimation);
                dialog.setCanceledOnTouchOutside(true);
                dialog.setCancelable(true);

                WindowManager m = AddCompanyActivity.this.getWindowManager();
                Display d = m.getDefaultDisplay(); // 获取屏幕宽、高度
                WindowManager.LayoutParams p = window.getAttributes(); // 获取对话框当前的参数值   
                p.width = (int) (d.getWidth() * 1); // 宽度设置为屏幕的1，根据实际情况调整
                window.setAttributes(p);

                no.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View view) {
                        dialog.dismiss();
                    }
                });

                yes.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View view) {
                        address.setText(mCurrentProviceName+mCurrentCityName+mCurrentDistrictName);
                        dialog.dismiss();
                    }
                });
            }
        });

        layout.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Intent intent = new Intent(AddCompanyActivity.this,TicketActivity.class);
                intent.putExtra("name",detailName.getText().toString());
                startActivityForResult(intent,0);
            }
        });

        go.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if (detailName.getText().toString().length() == 0){
                    Toast.makeText(AddCompanyActivity.this, "请输入公司名称", Toast.LENGTH_SHORT).show();
                    return;
                }
                if (address.getText().toString().length() == 0){
                    Toast.makeText(AddCompanyActivity.this, "请选择所在地区", Toast.LENGTH_SHORT).show();
                    return;
                }
                if (detailAddress.getText().toString().length() == 0){
                    Toast.makeText(AddCompanyActivity.this, "请输入详细地址", Toast.LENGTH_SHORT).show();
                    return;
                }

                find();

            }
        });
    }

    private void find(){

        Company add = new Company();
        add.setUserId(sharedPreferences.getInt("userId",0));
        add.setCompanyDetailName(detailName.getText().toString());
        add.setCompanyName(name.getText().toString());
        add.setPerson(person.getText().toString());
        add.setIndustry(industry.getText().toString());
        add.setMoney(money.getText().toString());
        add.setAddress(address.getText().toString());
        add.setDetailAddress(detailAddress.getText().toString());
        add.setRemarks(remarks.getText().toString());
        add.setCompanyNumber(ticketNumber);
        add.setCompanyAddress(companyAddress);
        add.setCompanyIphone(companyIphone);
        add.setBankName(bankName);
        add.setBankNumber(bankNumber);
        add.save(new SaveListener<String>() {
            @Override
            public void done(String s, BmobException e) {
                if (e == null){
                    Toast.makeText(AddCompanyActivity.this, "保存成功", Toast.LENGTH_SHORT).show();
                    CompanyActivity.companyActivity.find();
                    finish();
                }else {
                    Toast.makeText(AddCompanyActivity.this, "保存失败，请联系管理员，qq:389617853", Toast.LENGTH_SHORT).show();
                }
            }
        });


    }


    private void personClick(){
        View view = LayoutInflater.from(this).inflate(R.layout.sekect_people_number,null);
        TextView tv1 = (TextView)view.findViewById(R.id.tv1);
        TextView tv2 = (TextView)view.findViewById(R.id.tv2);
        TextView tv3 = (TextView)view.findViewById(R.id.tv3);
        TextView tv4 = (TextView)view.findViewById(R.id.tv4);
        TextView tv5 = (TextView)view.findViewById(R.id.tv5);
        TextView tv6 = (TextView)view.findViewById(R.id.tv6);
        TextView no = (TextView)view.findViewById(R.id.no);

        AlertDialog dialog = new AlertDialog.Builder(this,R.style.DialogStyle)
                .setView(view)
                .create();
        dialog.show();

        tv1.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                person.setText("10人及以下");
                dialog.dismiss();
            }
        });
        tv2.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                person.setText("10人-50人");
                dialog.dismiss();
            }
        });
        tv3.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                person.setText("50人-100人");
                dialog.dismiss();
            }
        });
        tv4.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                person.setText("100人-500人");
                dialog.dismiss();
            }
        });
        tv5.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                person.setText("500人-1000人");
                dialog.dismiss();
            }
        });
        tv6.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                person.setText("100人以上");
                dialog.dismiss();
            }
        });
        no.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                dialog.dismiss();
            }
        });


        Window window = dialog.getWindow();
        window.setGravity(Gravity.BOTTOM);
        window.setWindowAnimations(R.style.popupAnimation);
        dialog.setCanceledOnTouchOutside(true);
        dialog.setCancelable(true);

        WindowManager m = this.getWindowManager();
        Display d = m.getDefaultDisplay(); // 获取屏幕宽、高度
        WindowManager.LayoutParams p = window.getAttributes(); // 获取对话框当前的参数值   
        p.width = (int) (d.getWidth() * 0.92); // 宽度设置为屏幕的0.92，根据实际情况调整
        window.setAttributes(p);


    }

    private void industryClick(){
        View view = LayoutInflater.from(this).inflate(R.layout.industry,null);
        TextView tv1 = (TextView)view.findViewById(R.id.tv1);
        TextView tv2 = (TextView)view.findViewById(R.id.tv2);
        TextView tv3 = (TextView)view.findViewById(R.id.tv3);
        TextView tv4 = (TextView)view.findViewById(R.id.tv4);
        TextView tv5 = (TextView)view.findViewById(R.id.tv5);
        TextView tv6 = (TextView)view.findViewById(R.id.tv6);
        TextView tv7 = (TextView)view.findViewById(R.id.tv7);
        TextView tv8 = (TextView)view.findViewById(R.id.tv8);
        TextView tv9 = (TextView)view.findViewById(R.id.tv9);
        TextView tv10 = (TextView)view.findViewById(R.id.tv10);
        TextView no = (TextView)view.findViewById(R.id.no);
        AlertDialog dialog = new AlertDialog.Builder(this,R.style.DialogStyle)
                .setView(view)
                .create();
        dialog.show();

        tv1.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                industry.setText("油贸");
                dialog.dismiss();
            }
        });

        tv2.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                industry.setText("公路运输");
                dialog.dismiss();
            }
        });

        tv3.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                industry.setText("工矿企业");
                dialog.dismiss();
            }
        });

        tv4.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                industry.setText("建筑");
                dialog.dismiss();
            }
        });

        tv5.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                industry.setText("农业");
                dialog.dismiss();
            }
        });

        tv6.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                industry.setText("水路运输");
                dialog.dismiss();
            }
        });

        tv7.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                industry.setText("电力");
                dialog.dismiss();
            }
        });

        tv8.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                industry.setText("渔业");
                dialog.dismiss();
            }
        });

        tv9.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                industry.setText("商业及民用");
                dialog.dismiss();
            }
        });

        tv10.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                industry.setText("铁路运输");
                dialog.dismiss();
            }
        });


        Window window = dialog.getWindow();
        window.setGravity(Gravity.BOTTOM);
        window.setWindowAnimations(R.style.popupAnimation);
        dialog.setCanceledOnTouchOutside(true);
        dialog.setCancelable(true);

        WindowManager m = this.getWindowManager();
        Display d = m.getDefaultDisplay(); // 获取屏幕宽、高度
        WindowManager.LayoutParams p = window.getAttributes(); // 获取对话框当前的参数值   
        p.width = (int) (d.getWidth() * 0.92); // 宽度设置为屏幕的0.92，根据实际情况调整
        window.setAttributes(p);


    }

    private void moneyClick(){
        View view = LayoutInflater.from(this).inflate(R.layout.sekect_people_number,null);
        TextView tv1 = (TextView)view.findViewById(R.id.tv1);
        TextView tv2 = (TextView)view.findViewById(R.id.tv2);
        TextView tv3 = (TextView)view.findViewById(R.id.tv3);
        TextView tv4 = (TextView)view.findViewById(R.id.tv4);
        TextView tv5 = (TextView)view.findViewById(R.id.tv5);
        TextView tv6 = (TextView)view.findViewById(R.id.tv6);
        TextView no = (TextView)view.findViewById(R.id.no);

        tv1.setText("500万以下");
        tv2.setText("500万-1000万");
        tv3.setText("1000万-5000万");
        tv4.setText("5000万-1亿");
        tv5.setText("1亿-10亿");
        tv6.setText("10亿以上");

        AlertDialog dialog = new AlertDialog.Builder(this,R.style.DialogStyle)
                .setView(view)
                .create();
        dialog.show();

        tv1.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                money.setText("500万以下");
                dialog.dismiss();
            }
        });
        tv2.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                money.setText("500万-1000万");
                dialog.dismiss();
            }
        });
        tv3.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                money.setText("1000万-5000万");
                dialog.dismiss();
            }
        });
        tv4.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                money.setText("5000万-1亿");
                dialog.dismiss();
            }
        });
        tv5.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                money.setText("1亿-10亿");
                dialog.dismiss();
            }
        });
        tv6.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                money.setText("10亿以上");
                dialog.dismiss();
            }
        });
        no.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                dialog.dismiss();
            }
        });


        Window window = dialog.getWindow();
        window.setGravity(Gravity.BOTTOM);
        window.setWindowAnimations(R.style.popupAnimation);
        dialog.setCanceledOnTouchOutside(true);
        dialog.setCancelable(true);

        WindowManager m = this.getWindowManager();
        Display d = m.getDefaultDisplay(); // 获取屏幕宽、高度
        WindowManager.LayoutParams p = window.getAttributes(); // 获取对话框当前的参数值   
        p.width = (int) (d.getWidth() * 0.92); // 宽度设置为屏幕的0.92，根据实际情况调整
        window.setAttributes(p);

    }

    private void setUpListener() {
        // 添加change事件
        mViewProvince.addChangingListener(AddCompanyActivity.this);
        // 添加change事件
        mViewCity.addChangingListener(this);
        // 添加change事件
        mViewDistrict.addChangingListener(this);
    }

    private void setUpData() {
        initProvinceDatas();
        mViewProvince.setViewAdapter(new ArrayWheelAdapter<String>(AddCompanyActivity.this, mProvinceDatas));
        // 设置可见条目数量
        mViewProvince.setVisibleItems(6);
        mViewCity.setVisibleItems(6);
        mViewDistrict.setVisibleItems(6);
        updateCities();
        updateAreas();
    }


    /**
     * 根据当前的市，更新区WheelView的信息
     */
    private void updateAreas() {
        int pCurrent = mViewCity.getCurrentItem();
        mCurrentCityName = mCitisDatasMap.get(mCurrentProviceName)[pCurrent];
        String[] areas = mDistrictDatasMap.get(mCurrentCityName);

        if (areas == null) {
            areas = new String[] { "" };
        }
        mViewDistrict.setViewAdapter(new ArrayWheelAdapter<String>(this, areas));
        mViewDistrict.setCurrentItem(0);
    }

    /**
     * 根据当前的省，更新市WheelView的信息
     */
    private void updateCities() {
        int pCurrent = mViewProvince.getCurrentItem();
        mCurrentProviceName = mProvinceDatas[pCurrent];
        String[] cities = mCitisDatasMap.get(mCurrentProviceName);
        if (cities == null) {
            cities = new String[] { "" };
        }
        mViewCity.setViewAdapter(new ArrayWheelAdapter<String>(this, cities));
        mViewCity.setCurrentItem(0);
        updateAreas();
    }

    @Override
    public void onClick(View view) {

    }

    @Override
    public void onChanged(WheelView wheel, int oldValue, int newValue) {
        // TODO Auto-generated method stub
        if (wheel == mViewProvince) {
            updateCities();
        } else if (wheel == mViewCity) {
            updateAreas();
        } else if (wheel == mViewDistrict) {
            mCurrentDistrictName = mDistrictDatasMap.get(mCurrentCityName)[newValue];
            mCurrentZipCode = mZipcodeDatasMap.get(mCurrentDistrictName);
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        switch (resultCode){
            case 0:
                try {
                    Bundle bundle = data.getExtras();
                    companyName = bundle.getString("companyName");
                    ticketNumber = bundle.getString("ticketNumber");
                    companyAddress = bundle.getString("companyAddress");
                    companyIphone = bundle.getString("companyIphone");
                    bankName = bundle.getString("bankName");
                    bankNumber = bundle.getString("bankNumber");
                    state.setText("已添加开票信息");

                }catch (NullPointerException e){
                    e.printStackTrace();
                }
                break;
            default:
                break;
        }
    }
}
